package org.wisdom.ac.domain.resource.repository.dao.impl;

import org.wisdom.ac.domain.resource.entity.AcResource;
import org.wisdom.ac.domain.resource.repository.dao.ResourceDao;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.List;

/**
 * 资源仓储扩展API
 *
 * @author 张智研
 * @date 2022/06/02 12:42
 **/
public class ResourceDaoImpl implements ResourceDao {
    @PersistenceContext
    private EntityManager em;

    @Override
    public List<AcResource> findAllByUserId(String userId) {
        String jpql =
            "select distinct r from AcResource r, AcUserRole ur, AcRoleResource rr where r.id = rr.resourceId and rr.roleId = ur.roleId and ur.userId = :userId";
        TypedQuery<AcResource> query = this.em.createQuery(jpql, AcResource.class);

        query.setParameter("userId", userId);
        // 去除N+1查询
        query.setHint("javax.persistence.fetchgraph", this.em.getEntityGraph("roleWithResource"));

        return query.getResultList();
    }

    @Override
    public boolean hasPermission(String userId, String permission) {
        String jpql =
                "select distinct r from AcResource r, AcUserRole ur, AcRoleResource rr where r.id = rr.resourceId and rr.roleId = ur.roleId and ur.userId = :userId and r.permission = :permission";
        TypedQuery<AcResource> query = this.em.createQuery(jpql, AcResource.class);
        query.setParameter("userId", userId);
        query.setParameter("permission",permission);
        // 去除N+1查询
        query.setHint("javax.persistence.fetchgraph", this.em.getEntityGraph("roleWithResource"));

        return query.getResultList().size() > 0;
    }
}
